package yf.mall.sms;

import com.alibaba.fastjson.JSONObject;
import com.yf.response.RRException;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class ChuangLanSms {

   public static void sendCaptcha(String phone,String captcha){
        //短信下发
        String sendUrl = "https://smssh1.253.com/msg/v1/send/json";
        Map map = new HashMap();
        map.put("account","YZM737915_YZM4752247");//API账号
        map.put("password","beNhcBJDi2fb87");//API密码
        map.put("msg","【抖鑫集团】您的验证码为:"+captcha+"，请勿泄露于他人!");//短信内容
        map.put("phone",phone);//手机号
        map.put("report","true");//是否需要状态报告
//        map.put("extend","123");//自定义扩展码
        JSONObject js = (JSONObject) JSONObject.toJSON(map);
        String res = sendSmsByPost(sendUrl,js.toString());
        log.error("ChuangLan短信结果:{},{}",phone,res);
        JSONObject result = JSONObject.parseObject(res);
        if(!result.getString("code").equals("0")){
            throw new RRException("短信发送失败");
        }
        //查询余额
//        String balanceUrl = "https://smssh1.253.com/msg/balance/json";
//        Map map1 = new HashMap();
//        map1.put("account","N*******");
//        map1.put("password","************");
//        JSONObject js1 = (JSONObject) JSONObject.toJSON(map1);
    }


    private static String sendSmsByPost(String path, String postContent) {
        URL url = null;
        try {
            url = new URL(path);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setConnectTimeout(10000);
            httpURLConnection.setReadTimeout(10000);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.connect();
            OutputStream os=httpURLConnection.getOutputStream();
            os.write(postContent.getBytes("UTF-8"));
            os.flush();
            StringBuilder sb = new StringBuilder();
            int httpRspCode = httpURLConnection.getResponseCode();
            if (httpRspCode == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                return sb.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
